#!/usr/bin/env python3
"""
命令行文本计数统计程序
支持统计字符数、单词数、句子数
"""

import sys
import os
import re


def count_characters(text):
    """统计字符数（包括空格和标点）"""
    return len(text)


def count_words(text):
    """统计单词数"""
    # 使用正则表达式匹配单词（字母数字序列）
    words = re.findall(r'\b[a-zA-Z]+\b', text)
    return len(words)


def count_sentences(text):
    """统计句子数"""
    # 简单的句子分割：以 . ! ? 结尾作为句子
    sentences = re.split(r'[.!?]+', text)
    # 过滤空字符串
    sentences = [s.strip() for s in sentences if s.strip()]
    return len(sentences)


def read_file(file_path):
    """读取文件内容"""
    try:
        with open(file_path, 'r', encoding='utf-8') as file:
            return file.read()
    except FileNotFoundError:
        print(f"错误：文件 '{file_path}' 未找到")
        return None
    except Exception as e:
        print(f"读取文件时出错：{e}")
        return None


def print_usage():
    """打印使用说明"""
    print("用法: wc.exe [参数] [文件名]")
    print("参数:")
    print("  -c  统计字符数")
    print("  -w  统计单词数")
    print("  -s  统计句子数")
    print("  -a  统计所有信息")
    print("示例:")
    print("  wc.exe -c file.txt")
    print("  wc.exe -a file.txt")


def main():
    if len(sys.argv) != 3:
        print_usage()
        sys.exit(1)

    param = sys.argv[1]
    file_path = sys.argv[2]

    # 检查文件是否存在
    if not os.path.exists(file_path):
        print(f"错误：文件 '{file_path}' 不存在")
        sys.exit(1)

    # 读取文件内容
    text = read_file(file_path)
    if text is None:
        sys.exit(1)

    # 根据参数执行相应操作
    if param == '-c':
        char_count = count_characters(text)
        print(f"字符数: {char_count}")

    elif param == '-w':
        word_count = count_words(text)
        print(f"单词数: {word_count}")

    elif param == '-s':
        sentence_count = count_sentences(text)
        print(f"句子数: {sentence_count}")

    elif param == '-a':
        char_count = count_characters(text)
        word_count = count_words(text)
        sentence_count = count_sentences(text)

        print(f"字符数: {char_count}")
        print(f"单词数: {word_count}")
        print(f"句子数: {sentence_count}")

    else:
        print(f"错误：未知参数 '{param}'")
        print_usage()
        sys.exit(1)


if __name__ == "__main__":
    main()